package cn.com.redenvelope.redis;

import cn.com.redenvelope.AbstractRedEnvelopeCreator;
import cn.com.redenvelope.RedEnvelopeCreateResult;
import cn.com.redenvelope.RedEnvelopeCreateListener;
import cn.com.redis.RedisDistributionConnectionTool;
import redis.clients.jedis.ShardedJedis;

public class RedisRedEnvelopeCreator extends AbstractRedEnvelopeCreator{

	private int expireSeconds = 3600 * 24;
	
	public RedisRedEnvelopeCreator(int expireSeconds) {
		this.expireSeconds = expireSeconds;
	}
	
	@Override
	public RedEnvelopeCreateResult createEnvelope(int envelopeId, int money, int count, int type, RedEnvelopeCreateListener listener) {
		
		RedisDistributionConnectionTool redisTool = new RedisDistributionConnectionTool();
		ShardedJedis client = redisTool.getRedisClient();
		
		String key = "ev:" + envelopeId;
		
		RedEnvelopeCreateResult result = RedEnvelopeCreateResult.CREATE_FAILURE;
		
		try {
			//红包是否在redis里存在，存在则说明该红包现在还没抢完
			//不存在，需要先检查该红包的实际状态，只有实际状态可以发红包才创建红包
			if (client.exists(key)) {
				if (client.llen(key) > 0) {
					result = RedEnvelopeCreateResult.HAS_CREATED;
				} else {
					result = RedEnvelopeCreateResult.COMPLETED;
				}
			} else {
				if (listener.beforeCreateEnvelope()) {
					int[] everyMoney = this.generateEnvelopeMoney(money, count, type);
					
					if (everyMoney.length == 1 && everyMoney[0] == -1) {
						result = RedEnvelopeCreateResult.CREATE_FAILURE;
					} else {
						this.initRedisEnvelopeQueue(client, key, everyMoney);	
						
						if (listener.afterCreateEnvelope()) {
							result = RedEnvelopeCreateResult.CREATE_SUCCESS;
						} else {
							result = RedEnvelopeCreateResult.CREATE_SUCCESS;
						}
					}
				}
			}
			redisTool.returnClientResource();
		} catch (Exception ex) {
			result = RedEnvelopeCreateResult.CREATE_FAILURE;
			ex.printStackTrace();
		} finally {
			redisTool.returnBrokenClientResource();
		}
		
				
		return result;
	}
	
	/**
	 * 初始化redis的红包队列
	 * @param client
	 * @param key
	 * @param everyMoney
	 */
	private void initRedisEnvelopeQueue(ShardedJedis client, String key, int[] everyMoney) {
		for (int i=0; i<everyMoney.length; i++) {
			client.rpush(key, String.valueOf(everyMoney[i]));
		}
		
		client.expire(key, this.expireSeconds);
	}

}
